// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

package utils

import (
	"crypto/sha256"
	"crypto/sha512"
	"encoding/hex"
	"io"
	"os"

	"github.com/kumose/kmopt/pkg/repository/v1manifest"
)

// HashFile returns the sha256/sha512 hashes and the file length of specific file
func HashFile(filepath string) (map[string]string, int64, error) {
	s256 := sha256.New()
	s512 := sha512.New()
	file, err := os.Open(filepath)
	if err != nil {
		return nil, 0, err
	}
	defer file.Close()

	n, err := io.Copy(io.MultiWriter(s256, s512), file)

	hashes := map[string]string{
		v1manifest.SHA256: hex.EncodeToString(s256.Sum(nil)),
		v1manifest.SHA512: hex.EncodeToString(s512.Sum(nil)),
	}
	return hashes, n, err
}
